# -*- coding: utf-8 -*-
"""现代UI主题模块 - 提供租赁合同管理系统的现代感界面设计"""

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor, QFont


class ModernTheme:
    """现代主题类 - 定义淡雅大气的UI样式"""
    
    # 预定义的主题方案
    THEMES = {
        'default': {
            'background': '#f5f5f5',       # 浅灰色背景
            'secondary': '#e0e0e0',        # 次要背景色
            'background_alt': '#f0f0f0',   # 替代背景色
            'text': '#000000',             # 主要文本色（改为黑色）
            'text_light': '#777777',       # 次要文本色
            'primary': '#4CAF50',          # 主色调（淡绿色）
            'primary_light': '#66BB6A',    # 亮色主色调
            'primary_dark': '#388E3C',     # 暗色主色调
            'accent': '#e74c3c',           # 强调色（红色）
            'danger': '#c0392b',           # 危险色
            'success': '#2ecc71',          # 成功色
            'warning': '#f39c12',          # 警告色
            'border': '#cccccc',           # 边框颜色
            'button_text': '#ffffff',      # 按钮文本色（白色）
        },
        'dark': {
            'background': '#1a1a1a',       # 主背景色，符合深色主题标准
            'secondary': '#2a2a2a',        # 次要背景色，保持层次感
            'background_alt': '#333333',   # 替代背景色，稍微亮一点以提高可读性
            'text': '#ffffff',             # 主要文本色（白色），与深色背景形成高对比度
            'text_light': '#e0e0e0',       # 次要文本色，提高亮度确保与所有背景的对比度≥4.5:1
            'primary': '#66BB6A',          # 主色调（调整为中等亮度绿色），确保按钮文本对比度
            'primary_light': '#81C784',    # 亮色主色调，调整为更亮的绿色
            'primary_dark': '#4CAF50',     # 暗色主色调
            'accent': '#FF7043',           # 强调色（亮橙色），保持良好对比度
            'danger': '#EF5350',           # 危险色，保持良好对比度
            'success': '#4CAF50',          # 成功色，调整为更深的绿色
            'warning': '#FFA726',          # 警告色，保持良好对比度
            'border': '#555555',           # 边框颜色，稍微亮一点以提高可见性
            'highlight': '#81C784',        # 高亮色，确保焦点清晰可见
            'tooltip_bg': '#333333',       # 提示框背景色，稍微亮一点以提高文本可读性
            'button_text': '#ffffff',      # 按钮文本色，确保在所有按钮背景上都有良好对比度
        },
        'blue': {
            'background': '#f0f4f8',       # 浅蓝色背景
            'secondary': '#d0e1f9',        # 次要背景色
            'background_alt': '#e1ebf7',   # 替代背景色
            'text': '#000000',             # 主要文本色（黑色）
            'text_light': '#555555',       # 次要文本色
            'primary': '#1976D2',          # 主色调（深蓝色）
            'primary_light': '#42A5F5',    # 亮色主色调
            'primary_dark': '#1565C0',     # 暗色主色调
            'accent': '#2196F3',           # 强调色（中蓝色）
            'danger': '#d32f2f',           # 危险色
            'success': '#388E3C',          # 成功色
            'warning': '#F57C00',          # 警告色
            'border': '#BBDEFB',           # 边框颜色
            'button_text': '#ffffff',      # 按钮文本色（白色）
        },
        'classic': {
            'background': '#ffffff',       # 白色背景
            'secondary': '#f0f0f0',        # 次要背景色
            'background_alt': '#f5f5f5',   # 替代背景色
            'text': '#000000',             # 主要文本色（黑色）
            'text_light': '#666666',       # 次要文本色
            'primary': '#0277BD',          # 主色调（深蓝色）
            'primary_light': '#03A9F4',    # 亮色主色调
            'primary_dark': '#01579B',     # 暗色主色调
            'accent': '#FF5722',           # 强调色（橙色）
            'danger': '#C62828',           # 危险色
            'success': '#2E7D32',          # 成功色
            'warning': '#E65100',          # 警告色
            'border': '#dddddd',           # 边框颜色
            'button_text': '#ffffff',      # 按钮文本色（白色）
        }
    }
    
    def __init__(self, theme_name='default'):
        """初始化主题
        
        Args:
            theme_name: 主题名称，可选值：'default', 'dark', 'blue', 'classic'
        """
        self.theme_name = theme_name
        self.set_theme(theme_name)
    
    def set_theme(self, theme_name):
        """切换主题
        
        Args:
            theme_name: 主题名称
        """
        if theme_name in self.THEMES:
            self.theme_name = theme_name
            self.colors = self.THEMES[theme_name].copy()
        else:
            # 如果指定的主题不存在，使用默认主题
            self.theme_name = 'default'
            self.colors = self.THEMES['default'].copy()
        
        self.font_family = 'Arial, SimHei, sans-serif'
        self.font_sizes = {
            'small': 11,
            'normal': 13,
            'medium': 15,
            'large': 17,
            'xlarge': 19,
        }
        
        self.border_radius = 6
    
    def apply_theme(self, app):
        """应用主题到应用程序"""
        app.setStyleSheet(self.get_stylesheet())
        
        first_font = self.font_family.split(',')[0].strip()
        font = QFont(first_font, self.font_sizes['normal'])
        app.setFont(font)
    
    def get_stylesheet(self):
        """获取完整的CSS样式表"""
        # 使用字典替换而不是复杂的格式化，避免类型错误
        styles = {
            'font_family': self.font_family,
            'font_size_normal': str(self.font_sizes['normal']),
            'font_size_large': str(self.font_sizes['large']),
            'font_size_medium': str(self.font_sizes['medium']),
            'font_size_xlarge': str(self.font_sizes['xlarge']),
            'border_radius': str(self.border_radius),
            'background': self.colors['background'],
            'secondary': self.colors['secondary'],
            'background_alt': self.colors['background_alt'],
            'text': self.colors['text'],
            'text_light': self.colors['text_light'],
            'primary': self.colors['primary'],
            'primary_light': self.colors['primary_light'],
            'primary_dark': self.colors['primary_dark'],
            'accent': self.colors['accent'],
            'danger': self.colors['danger'],
            'success': self.colors['success'],
            'warning': self.colors['warning'],
            'border': self.colors['border'],
            'button_text': self.colors.get('button_text', '#ffffff')  # 添加按钮文本颜色
        }
        
        # 添加主题特有的颜色
        for key in ['highlight', 'tooltip_bg']:
            if key in self.colors:
                styles[key] = self.colors[key]
        
        # 构建基础样式表
        stylesheet = """
            * {
                font-family: '%(font_family)s';
                font-size: %(font_size_normal)spx;
                border-radius: %(border_radius)spx;
            }
            
            QMainWindow { background-color: %(background)s; }
            
            QTabWidget { background-color: %(background)s; border: none; padding: 10px; }
            QTabBar { background-color: %(background)s; padding-top: 5px; padding-bottom: 5px; }
            QTabBar::tab { 
                background-color: %(secondary)s; color: %(text)s; 
                border: none; padding: 10px 20px; margin-right: 5px; 
                font-size: %(font_size_normal)spx; 
            }
            QTabBar::tab:selected { 
                background-color: %(primary)s; color: %(background)s; font-weight: 550; /* 增加权重以提高可见性 */
            }
            
            QPushButton { 
                background-color: %(primary)s; color: %(button_text)s; 
                border: none; padding: 8px 16px; min-width: 80px; 
                font-size: %(font_size_normal)spx; 
                font-weight: 500; /* 增加字体权重以提高可读性 */
            }
            QPushButton:hover { background-color: %(primary_light)s; }
            QPushButton:pressed { background-color: %(primary_dark)s; }
            QPushButton:disabled { background-color: %(border)s; color: %(text_light)s; }
            
            QPushButton#secondary-button { background-color: %(secondary)s; color: %(button_text)s; font-weight: 500; }
            QPushButton#secondary-button:hover { background-color: %(border)s; }
            QPushButton#danger-button { background-color: %(danger)s; }
            QPushButton#danger-button:hover { background-color: %(accent)s; }
            QPushButton#success-button { background-color: %(success)s; }
            
            QTableWidget { 
                background-color: %(background)s; border: 1px solid %(border)s; 
                gridline-color: %(border)s; selection-background-color: %(primary_dark)s; 
                selection-color: %(button_text)s; alternate-background-color: %(background_alt)s; 
            }
            QTableWidget::item { padding: 5px; border: none; }
            QTableWidget::item:selected { background-color: %(primary_dark)s; color: %(button_text)s; }
            QHeaderView::section { 
                background-color: %(secondary)s; color: %(text)s; 
                padding: 8px; border: 1px solid %(border)s; 
                text-align: center; font-weight: bold; 
            }
            
            QGroupBox { 
                background-color: %(background)s; border: 1px solid %(border)s; 
                border-radius: %(border_radius)spx; margin-top: 10px; padding: 10px; 
            }
            QGroupBox::title { 
                subcontrol-origin: margin; subcontrol-position: top left; 
                padding: 0 5px; background-color: %(background)s; 
                color: %(text)s; font-weight: bold; 
            }
            
            QLineEdit, QComboBox, QDateEdit, QTextEdit, QDoubleSpinBox, QSpinBox { 
                background-color: %(background_alt)s; border: 1px solid %(border)s; 
                padding: 6px; color: %(text)s; 
                font-weight: 450; /* 稍微增加权重以提高可读性 */
            }
            QLineEdit:focus, QComboBox:focus, QDateEdit:focus, QTextEdit:focus, 
            QDoubleSpinBox:focus, QSpinBox:focus { 
                border: 2px solid %(primary)s; outline: none; 
            }
            
            QScrollBar:vertical { background-color: %(background_alt)s; width: 10px; margin: 0; }
            
            /* 确保所有禁用状态的文本仍有足够的对比度 */
            QAbstractButton:disabled, QAbstractSpinBox:disabled, 
            QComboBox:disabled, QDateEdit:disabled, QDateTimeEdit:disabled, 
            QDoubleSpinBox:disabled, QLineEdit:disabled, QSpinBox:disabled, 
            QTextEdit:disabled, QTimeEdit:disabled { 
                color: #a0a0a0; /* 确保禁用状态文本仍有足够对比度 */
                background-color: %(secondary)s; 
                border-color: %(border)s; 
            }
            QScrollBar::handle:vertical { background-color: %(border)s; min-height: 20px; }
            QScrollBar::handle:vertical:hover { background-color: %(primary)s; }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { background: none; }
            
            QLabel { color: %(text)s; background-color: transparent; font-weight: normal; }
            QLabel#title-label { 
                font-size: %(font_size_xlarge)spx; color: %(primary_dark)s; font-weight: bold; 
            }
            QLabel#subtitle-label { font-size: %(font_size_large)spx; color: %(text)s; }
            QLabel#stat-label { 
                font-size: %(font_size_medium)spx; color: %(primary)s; font-weight: bold; 
            }
            
            QDialog { background-color: %(background)s; border-radius: %(border_radius)spx; }
            
            QProgressBar { 
                background-color: %(background_alt)s; border: none; 
                text-align: center; color: %(text)s; height: 10px; 
            }
            QProgressBar::chunk { background-color: %(primary)s; border-radius: 5px; }
            
            QFrame[frameShape="4"] { color: %(border)s; }
        """
        
        # 添加深色主题特定样式
        if self.theme_name == 'dark':
            dark_theme_styles = """
            /* 深色主题特定优化 */
            QMenu { 
                background-color: %(secondary)s; 
                border: 1px solid %(border)s; 
                color: %(text)s; 
                font-weight: 450; /* 稍微增加权重以提高可读性 */
            }
            QMenu::item { 
                background-color: transparent; 
                padding: 6px 25px 6px 25px; 
                color: %(text)s; 
            }
            QMenu::item:selected { 
                background-color: %(primary_dark)s; 
                color: %(button_text)s; 
                font-weight: 500; /* 增加权重以提高可读性 */
            }
            QMenu::item:disabled { 
                color: %(text_light)s; 
            }
            
            /* QComboBox下拉菜单样式适配 */
            QComboBox QAbstractItemView { 
                background-color: %(secondary)s; 
                color: %(text)s; 
                border: 1px solid %(border)s; 
                selection-background-color: %(primary_dark)s; 
                selection-color: %(button_text)s; 
            }
            
            /* 日历控件样式适配 */
            QCalendarWidget { 
                background-color: %(secondary)s; 
                color: %(text)s; 
                border: 1px solid %(border)s; 
            }
            QCalendarWidget QWidget { 
                color: %(text)s; 
            }
            QCalendarWidget QAbstractItemView:enabled { 
                background-color: %(background)s; 
                color: %(text)s; 
                selection-background-color: %(primary_dark)s; 
                selection-color: %(button_text)s; 
            }
            QCalendarWidget QAbstractItemView:disabled { 
                color: %(text_light)s; 
            }
            QCalendarWidget QToolButton { 
                color: %(text)s; 
                background-color: %(secondary)s; 
                border: none; 
            }
            QCalendarWidget QToolButton:hover { 
                background-color: %(primary)s; 
            }
            
            /* 状态栏样式 */
            QStatusBar { 
                background-color: %(secondary)s; 
                color: %(text_light)s; /* 使用稍微亮一点的文本色以提高可读性 */
                border-top: 1px solid %(border)s; 
                font-weight: 500; /* 增加字体权重以提高可读性 */
            }
            
            /* 深色主题下增强状态栏文本对比度 */
            QStatusBar::item { 
                color: %(text)s; /* 确保所有状态栏项使用相同的文本颜色 */
            }
            
            /* 分割线样式 */
            QSplitter::handle { 
                background-color: %(border)s; 
            }
            QSplitter::handle:hover { 
                background-color: %(primary)s; 
            }
            
            /* 滚动区域样式 */
            QScrollArea { 
                background-color: %(background)s; 
                border: none; 
            }
            
            /* 标签页容器样式 */
            QTabWidget::pane { 
                background-color: %(background)s; 
                border: 1px solid %(border)s; 
                border-top: none; 
            }
            
            /* 列表控件样式增强 */
            QListWidget, QTreeWidget { 
                background-color: %(background)s; 
                color: %(text)s; 
                border: 1px solid %(border)s; 
                selection-background-color: %(primary_dark)s; 
                selection-color: %(button_text)s; 
            }
            
            QListWidget::item, QTreeWidget::item { 
                padding: 5px; 
                border: none; 
            }
            
            /* 确保所有表格和列表项目在深色主题下有足够的对比度 */
            QAbstractItemView::item { 
                background-color: %(background)s; 
                color: %(text)s; 
                font-weight: 400; /* 保持正常文本权重 */
            }
            
            QAbstractItemView::item:selected { 
                background-color: %(primary_dark)s; 
                color: %(button_text)s; 
                font-weight: 500; /* 选中状态增加权重以提高可读性 */
            }
            
            /* 提示框样式 */
            QToolTip { 
                background-color: %(tooltip_bg)s; 
                color: %(text)s; 
                border: 1px solid %(border)s; 
                padding: 4px 8px; 
                border-radius: 4px; 
                font-weight: 500; /* 增加权重确保在提示框中的良好可读性 */
            }
            
            /* 禁用状态的通用样式 */
            QWidget:disabled { 
                color: %(text_light)s; 
            }
            
            /* 滚动条水平方向样式 */
            QScrollBar:horizontal { 
                background-color: %(background_alt)s; 
                height: 10px; 
                margin: 0; 
            }
            QScrollBar::handle:horizontal { 
                background-color: %(border)s; 
                min-width: 20px; 
            }
            QScrollBar::handle:horizontal:hover { 
                background-color: %(primary)s; 
            }
            QScrollBar::add-line:horizontal, 
            QScrollBar::sub-line:horizontal { 
                background: none; 
            }
            
            /* 复选框和单选按钮样式 */
            QCheckBox, QRadioButton { 
                color: %(text)s; 
                spacing: 5px; 
                font-weight: 450; /* 稍微增加权重以提高可读性 */
            }
            QCheckBox::indicator, QRadioButton::indicator { 
                width: 18px; 
                height: 18px; 
                border: 1px solid %(border)s; 
                background-color: %(secondary)s; 
            }
            QCheckBox::indicator:checked, QRadioButton::indicator:checked { 
                background-color: %(primary)s; 
                border: 1px solid %(primary)s; 
            }
            QCheckBox::indicator:disabled, QRadioButton::indicator:disabled { 
                background-color: %(background_alt)s; 
                border: 1px solid %(border)s; 
            }
            """
            stylesheet += dark_theme_styles
        
        # 使用字典格式化样式表
        return stylesheet % styles


class AnimationUtils:
    """动画工具类 - 提供UI动画效果"""
    
    @staticmethod
    def fade_in(widget, duration=300):
        """淡入效果"""
        from PyQt5.QtCore import QPropertyAnimation
        widget.setWindowOpacity(0)
        animation = QPropertyAnimation(widget, b"windowOpacity")
        animation.setDuration(duration)
        animation.setStartValue(0)
        animation.setEndValue(1)
        animation.start()
    
    @staticmethod
    def slide_in(widget, direction="right", duration=300):
        """滑入效果"""
        from PyQt5.QtCore import QPropertyAnimation
        
        rect = widget.geometry()
        start_x, start_y = rect.x(), rect.y()
        width, height = rect.width(), rect.height()
        
        if direction == "right":
            widget.setGeometry(width, start_y, width, height)
        elif direction == "left":
            widget.setGeometry(-width, start_y, width, height)
        elif direction == "top":
            widget.setGeometry(start_x, -height, width, height)
        elif direction == "bottom":
            widget.setGeometry(start_x, height * 2, width, height)
        
        animation = QPropertyAnimation(widget, b"geometry")
        animation.setDuration(duration)
        animation.setEndValue(rect)
        animation.start()


class IconUtils:
    """图标工具类 - 提供图标相关功能"""
    
    @staticmethod
    def create_icon(color, size=16):
        """创建简单的彩色图标"""
        from PyQt5.QtGui import QIcon, QPixmap
        
        pixmap = QPixmap(size, size)
        pixmap.fill(QColor(color))
        return QIcon(pixmap)


def get_global_stylesheet(theme_name='default'):
    """获取全局样式表
    
    Args:
        theme_name: 主题名称，默认为'default'
    
    Returns:
        str: 全局样式表
    """
    # 获取指定主题
    theme = ModernTheme(theme_name)
    return theme.get_stylesheet()


def apply_global_theme(app, theme_name='default'):
    """应用全局主题
    
    Args:
        app: QApplication实例
        theme_name: 主题名称
    """
    theme = ModernTheme(theme_name)
    theme.apply_theme(app)